package com.mikufufu.blog.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mikufufu.blog.common.cache.RedisCache;
import com.mikufufu.blog.common.constant.RedisKey;
import com.mikufufu.blog.common.entity.AjaxResult;
import com.mikufufu.blog.common.entity.Query;
import com.mikufufu.blog.common.enums.FriendLinkStatus;
import com.mikufufu.blog.model.dto.api.FriendLinkParam;
import com.mikufufu.blog.model.entity.FriendLink;
import com.mikufufu.blog.model.vo.api.FriendLinkVO;
import com.mikufufu.blog.service.FriendLinkService;
import com.mikufufu.blog.utils.BeanUtil;
import com.mikufufu.blog.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/friendLink")
@Api(value="友链", tags = "友链")
public class FriendLinkController {

    @Autowired
    private FriendLinkService friendLinkService;

    @GetMapping("/page")
    @ApiOperation(value = "分页获取友链列表", notes = "分页获取友链列表")
    public AjaxResult<IPage<FriendLinkVO>> page(Query query,Integer status) {
        IPage<FriendLink> page = friendLinkService.page(query.getPage(),new LambdaQueryWrapper<FriendLink>()
                .eq(status != null,FriendLink::getStatus,status)
        );
        return AjaxResult.data(BeanUtil.copyPage(page, FriendLinkVO.class));
    }

    @GetMapping("/getTopLink")
    public AjaxResult<List<FriendLinkVO>> getTopLink() {
        return AjaxResult.data(friendLinkService.getTopLink());
    }


    @PostMapping("/apply")
    @ApiOperation(value = "友链申请", notes = "用于给申请友链的功能")
    public AjaxResult<Boolean> apply(@RequestBody @Validated FriendLinkParam friendLink) {
        String code = friendLink.getCode();
        String emailCode = RedisCache.get(RedisKey.EMAIL_CODE + friendLink.getEmail(), String.class);
        if(StringUtils.isBlank(emailCode) || !emailCode.equals(code)){
            return AjaxResult.error("验证码错误");
        }
        FriendLink entity = BeanUtil.copy(friendLink, FriendLink.class);
        entity.setStatus(FriendLinkStatus.REJECTED.getStatus());
        return AjaxResult.data(friendLinkService.save(entity));
    }
}
